package com.skyworth.web.wechat.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by yuhaichao on 2016/8/25.
 */
public class JsSign {

    public static Map<String,Object> paySign(String pkg,String appId){
        String signType="MD5";
        String nonceStr = RandomStringGenerator.getRandomStringByLength(32);
        String timeStamp = create_timestamp();
        Map<String,Object> ret = new HashMap<String, Object>();
        ret.put("appId", appId);
        ret.put("timeStamp", timeStamp);
        ret.put("nonceStr", nonceStr);
        ret.put("signType", signType);
        ret.put("package", pkg);
        String paySign=PaySignature.getSign(ret);
        ret.put("paySign", paySign);
        return ret;
    }


    public static Map<Object, Object> sign(String jsapi_ticket, String url, String appId) {
        Map<Object, Object> ret = new HashMap<Object, Object>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();

        String string1;
        String signature = "";

        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId", appId);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


}
